﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BestBuy.DAL;
using BestBuy.UserControl;
using BestBuy.Common;

namespace BestBuy.PageUser
{
    public partial class EditBuyOffer : System.Web.UI.Page
    {
        cBangTinMua cBangTinMua = new cBangTinMua();
        cDonVi cDonVi = new cDonVi();
        const int MaxQuantity = 3;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["IDDN"].ToString().Equals(""))
            {
                Response.Redirect("~/Account/Login.aspx");
            }
            if (!Page.IsPostBack)
            {
                LoadComboboxDonVi();
                if (Request.Params["IDBangTinMua"] != null)
                {
                    LoadInfoProduct(int.Parse(Request.Params["IDBangTinMua"].ToString()));
                    HiddenIDBangTinMua.Value = Request.Params["IDBangTinMua"].ToString();
                }
                LoadCategoriesIntoListBox(gvLevel1, null);
            }
        }

        private void ClearPage()
        {
            CategoryListBox.Items.Clear();
            cbAnnualPurchaseVolume.SelectedIndex = 0;
            cbBuyingFrequency.SelectedIndex = 0;
            cbExpiryTime.SelectedIndex = 0;
            cbQuantityRequired.SelectedIndex = 0;
            for (int i = 0; i < PaymentCheckBoxList.Items.Count; i++)
            {
                PaymentCheckBoxList.Items[i].Selected = false;
            }
            lbThongBao.Visible = false;
        }

        private bool LoadCategoriesIntoListBox(GridView control, int? parentCatID)
        {
            var cats = cBangTinMua.GetChildrenOfCategory(parentCatID);
            control.DataSource = cats;
            control.DataBind();
            return cats != null && cats.Count > 0;
        }
        
        private void LoadComboboxDonVi()
        {
            cbAnnualPurchaseVolume.DataSource = cDonVi.GetAll();
            cbAnnualPurchaseVolume.DataTextField = "TenDonVi";
            cbAnnualPurchaseVolume.DataValueField = "IDDonVi";
            cbAnnualPurchaseVolume.DataBind();
            cbQuantityRequired.DataSource = cDonVi.GetAll();
            cbQuantityRequired.DataTextField = "TenDonVi";
            cbQuantityRequired.DataValueField = "IDDonVi";
            cbQuantityRequired.DataBind();
        }

        private void LoadInfoProduct(int ID)
        {
            ClearPage();
            BangTinMua item = cBangTinMua.GetByID(ID);
            if (item != null)
            {
                foreach (DanhMucMua i in item.DanhMucMuas)
                {
                    ListItem listItem = new ListItem();
                    listItem.Text = i.DanhMuc.TenDanhMuc;
                    listItem.Value = i.IDDanhMuc.ToString();
                    CategoryListBox.Items.Add(listItem);
                }
                txtTitle.Text = item.TieuDe;
                txtKeyword.Text = item.TuKhoa;
                txtDescription.Text = item.NoiDung;
                DateTime startDate = DateTime.Parse(item.NgayDang);
                DateTime endDate = DateTime.Parse(item.ThoiHanDang);
                int days = (endDate - startDate).Days;
                try
                {
                    cbExpiryTime.SelectedValue = days.ToString();
                }
                catch
                {
                    cbExpiryTime.SelectedIndex = 0;
                }

                cbBuyingFrequency.SelectedValue = item.TanSuatMuaHang.ToString();
                txtQuantityRequired.Text = item.SoLuongMua.ToString();
                if (item.IDDonVi != null)
                {
                    cbQuantityRequired.SelectedValue = item.IDDonVi.ToString();
                }
                txtAnnualPurchaseVolume.Text = item.KhoiLuongMuaHangNam.ToString();
                if (item.IDDonViHangNam != null)
                {
                    cbAnnualPurchaseVolume.SelectedValue = item.IDDonViHangNam.ToString();
                }
                txtShippingTerms.Text = item.KyHangGiaoHang;
                txtDestinationPort.Text = item.CangDen;
                string[] listPayment = item.PhuongThucThanhToan.Split('+');
                for (int vt=0; vt < listPayment.Length - 1;vt++)
                {
                    if (!listPayment[vt].Equals("0"))
                    {
                        PaymentCheckBoxList.Items[vt].Selected = true;
                    }
                }
                
            }
        }

        private bool ExistCategoryInList(int IDCategory)
        {
            foreach (ListItem item in CategoryListBox.Items)
            {
                if (int.Parse(item.Value) == IDCategory)
                    return true;
            }
            return false;
        }

        private void AddCategoryToList(int IDCategory)
        {
            if (!ExistCategoryInList(IDCategory))
            {
                DanhMuc dm = cBangTinMua.GetCategoryByID(IDCategory);
                ListItem item = new ListItem();
                item.Value = dm.IDDanhMuc.ToString();
                item.Text = dm.TenDanhMuc;
                CategoryListBox.Items.Add(item);
            }
        }

        protected void btnAddCategory_OnClick(object sender, EventArgs e)
        {
            try
            {
                int id = 0;
                for (int i = 0; i < gvLevel1.Rows.Count; i++)
                {
                    if (CategoryListBox.Items.Count == MaxQuantity)
                    {
                        return;
                    }
                    CheckBox chk = (CheckBox)gvLevel1.Rows[i].FindControl("cbLevel");
                    if (chk != null)
                    {
                        if (chk.Checked == true && chk.Enabled == true)
                        {
                            id = int.Parse(chk.Attributes["ObjectId"]);
                            AddCategoryToList(id);
                        }
                    }
                }
                for (int i = 0; i < gvLevel2.Rows.Count; i++)
                {
                    if (CategoryListBox.Items.Count == MaxQuantity)
                    {
                        return;
                    }
                    CheckBox chk = (CheckBox)gvLevel2.Rows[i].FindControl("cbLevel");
                    if (chk != null)
                    {
                        if (chk.Checked == true && chk.Enabled == true)
                        {
                            id = int.Parse(chk.Attributes["ObjectId"]);
                            AddCategoryToList(id);
                        }
                    }
                }
                for (int i = 0; i < gvLevel3.Rows.Count; i++)
                {
                    if (CategoryListBox.Items.Count == MaxQuantity)
                    {
                        return;
                    }
                    CheckBox chk = (CheckBox)gvLevel3.Rows[i].FindControl("cbLevel");
                    if (chk != null)
                    {
                        if (chk.Checked == true && chk.Enabled == true)
                        {
                            id = int.Parse(chk.Attributes["ObjectId"]);
                            AddCategoryToList(id);
                        }
                    }
                }
                lbThongBaoAddCategory.Text = "Add categories success.";
                lbThongBaoAddCategory.CssClass = "success";
                lbThongBaoAddCategory.Visible = true;
            }
            catch 
            {
                lbThongBaoAddCategory.Text = "Add categories error.";
                lbThongBaoAddCategory.CssClass = "error";
                lbThongBaoAddCategory.Visible = true;
            }
            lbLimitQuantity.Text = MaxQuantity - CategoryListBox.Items.Count + "";
            this.mpeDanhMuc.Show();
        }

        protected void btnCancel_OnClick(object sender, EventArgs e)
        {
            lbThongBaoAddCategory.Visible = false;
            lbThongBaoAddCategory.Text = "";
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                int IDBangTinMua = int.Parse(HiddenIDBangTinMua.Value);
                BangTinMua item = new BangTinMua();
                DanhMucMua dm = null;

                item.IDBangTinMua = IDBangTinMua;
                item.DanhMucMuas.Clear();
                foreach (ListItem i in CategoryListBox.Items)
                {
                    dm = new DanhMucMua();
                    dm.IDBangTinMua = IDBangTinMua;
                    dm.IDDanhMuc = int.Parse(i.Value);
                    item.DanhMucMuas.Add(dm);
                }

                item.TieuDe = txtTitle.Text;
                item.TuKhoa = txtKeyword.Text;
                item.NoiDung = txtDescription.Text;
                DateTime date = DateTime.Today;
                date =  date.AddDays(int.Parse(cbExpiryTime.SelectedValue));
                item.ThoiHanDang = date.ToShortDateString();
                item.TanSuatMuaHang = int.Parse(cbBuyingFrequency.SelectedValue);
                item.SoLuongMua = null;
                item.IDDonVi = null;
                item.KhoiLuongMuaHangNam = null;
                item.IDDonViHangNam = null;
                if (!txtQuantityRequired.Text.Equals(""))
                {
                    item.SoLuongMua = int.Parse(txtQuantityRequired.Text);
                }
                if (cbQuantityRequired.SelectedIndex > 0)
                {
                    item.IDDonVi = int.Parse(cbQuantityRequired.SelectedValue);
                }
                if (!txtAnnualPurchaseVolume.Text.Equals(""))
                {
                    item.KhoiLuongMuaHangNam = int.Parse(txtAnnualPurchaseVolume.Text);
                }
                if (cbAnnualPurchaseVolume.SelectedIndex > 0)
                {
                    item.IDDonViHangNam = int.Parse(cbAnnualPurchaseVolume.SelectedValue);
                }
                item.KyHangGiaoHang = txtShippingTerms.Text;
                item.CangDen = txtDestinationPort.Text;
                string strPayment = "";
                for (int i = 0; i < PaymentCheckBoxList.Items.Count; i++)
                {
                    int check = 0;
                    if (PaymentCheckBoxList.Items[i].Selected)
                    {
                        check = i + 1;
                    }
                    strPayment += check + "+";
                }
                item.PhuongThucThanhToan = strPayment;

                cBangTinMua.Update(item);

                lbThongBao.Text = "Update is success";
                lbThongBao.CssClass = "InRight success DisplayInLine";
                lbThongBao.Visible = true;
            }
            catch
            {
                lbThongBao.Text = "Update is error";
                lbThongBao.CssClass = "InRight error DisplayInLine";
                lbThongBao.Visible = true;
            }
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            if (HiddenIDBangTinMua.Value != null)
            {
                LoadInfoProduct(int.Parse(HiddenIDBangTinMua.Value));
            }
        }

        protected void lbtnChangeCategory_Click(object sender, EventArgs e)
        {
            LoadCategoriesIntoListBox(gvLevel1, null);
            lbLimitQuantity.Text = MaxQuantity - CategoryListBox.Items.Count + "";
            this.mpeDanhMuc.Show();
        }

        protected void lbtnRemoveCategory_Click(object sender, EventArgs e)
        {
            if (CategoryListBox.SelectedItem != null)
            {
                int index = CategoryListBox.SelectedIndex;
                CategoryListBox.Items.RemoveAt(index);
            }
        }

        protected void LinkDanhMucLevel1_Click(object sender, EventArgs e)
        {
            LinkButton senderButton = sender as LinkButton;
            int id = 0;
            if (Int32.TryParse(senderButton.Attributes["ObjectId"], out id))
            {
                gvLevel3.DataSource = null;
                gvLevel3.DataBind();
                LoadCategoriesIntoListBox(gvLevel2, id);
            }
            this.mpeDanhMuc.Show();
        }

        protected void LinkDanhMucLevel2_Click(object sender, EventArgs e)
        {
            LinkButton senderButton = sender as LinkButton;
            int id = 0;
            if (Int32.TryParse(senderButton.Attributes["ObjectId"], out id))
            {
                LoadCategoriesIntoListBox(gvLevel3, id);
            }
            this.mpeDanhMuc.Show();
        }

        protected void LinkDanhMucLevel3_Click(object sender, EventArgs e)
        {
            this.mpeDanhMuc.Show();
        }

        protected void gvLevel1_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            LinkButton hidIDDanhMuc = (LinkButton)e.Row.FindControl("LinkDanhMuc");
            if (hidIDDanhMuc != null)
            {
                int id = Int32.Parse(hidIDDanhMuc.Attributes["ObjectId"]);
                if (!cBangTinMua.HasChildren(id))
                {
                    CheckBox checkbox = (CheckBox)e.Row.FindControl("cbLevel");
                    Label lb = (Label)e.Row.FindControl("lbLevel");
                    if (checkbox != null && lb != null)
                    {
                        checkbox.Visible = true;
                        lb.Visible = false;
                    }
                }
            }
        }
      
        protected void gvLevel2_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            LinkButton hidIDDanhMuc = (LinkButton)e.Row.FindControl("LinkDanhMuc");
            if (hidIDDanhMuc != null)
            {
                int id = Int32.Parse(hidIDDanhMuc.Attributes["ObjectId"]);
                if (!cBangTinMua.HasChildren(id))
                {
                    CheckBox checkbox = (CheckBox)e.Row.FindControl("cbLevel");
                    Label lb = (Label)e.Row.FindControl("lbLevel");
                    if (checkbox != null && lb != null)
                    {
                        checkbox.Visible = true;
                        lb.Visible = false;
                    }
                }
            }
        }
      
        protected void gvLevel3_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            LinkButton hidIDDanhMuc = (LinkButton)e.Row.FindControl("LinkDanhMuc");
            if (hidIDDanhMuc != null)
            {
                int id = Int32.Parse(hidIDDanhMuc.Attributes["ObjectId"]);
                if (!cBangTinMua.HasChildren(id))
                {
                    CheckBox checkbox = (CheckBox)e.Row.FindControl("cbLevel");
                    Label lb = (Label)e.Row.FindControl("lbLevel");
                    if (checkbox != null && lb != null)
                    {
                        checkbox.Visible = true;
                        lb.Visible = false;
                    }
                }
            }
        }

        protected void cbLevel_CheckedChanged(object sender, EventArgs e)
        {
            this.mpeDanhMuc.Show();
        }
    }
}